"""
用户service
最后修改：3.29
修改人：陈泯全
"""
from models.UserSubSysModels import Userclassifies, Expert, User
from flask import current_app, request
from utils.dataBase import db_session
from utils.tools import getRadomStr
from werkzeug.security import check_password_hash
from werkzeug.security import generate_password_hash


class userService(object):

    def __init__(self):
        pass

    """
    专家用户申请
    """

    def applyExpert(self, name, degree, userId, pic1, pic2, pic3):

        expert = Expert(name, degree, pic1, pic2, pic3, userId)
        db_session.add(expert)
        try:
            db_session.commit()
            current_app.logger.info('添加专家：{}'.format(expert))
        except Exception as r:
            current_app.logger.error(r)
            return 0
        return 1

    # 专家列表
    def expertlist(self):
        s = db_session.query(Expert).all()
        list = []
        if s is None:
            dict['status'] = 0
            list.append(dict)
        else:
            for item in s:
                dict = {}
                dict['eid'] = item.eid
                dict['userid'] = item.userid
                dict['ename'] = item.ename
                dict['edegree'] = item.edegree
                dict['pic1'] = item.pic1
                list.append(dict)
        return list

    # 搜索专家
    def search(self, str):
        express = "%" + str + "%"
        obj = db_session.query(Expert).filter(Expert.ename.like(express)).all()
        list = []
        if obj is None:
            dict['status'] = 0
            list.append(dict)
        else:
            for item in obj:
                dict = {}
                dict['eid'] = item.eid
                dict['userid'] = item.userid
                dict['ename'] = item.ename
                dict['edegree'] = item.edegree
                dict['pic1'] = item.pic1
                list.append(dict)
        return list

    # 专家详情
    def findbyid(self, id):
        obj = db_session.query(Expert).filter(Expert.eid == id).first()
        list = []
        dict = {}
        if obj is None:
            dict['status'] = 0
            list.append(dict)
        else:
            dict['eid'] = obj.eid
            dict['userid'] = obj.userid
            dict['ename'] = obj.ename
            dict['edegree'] = obj.edegree
            dict['pic1'] = obj.pic1
            list.append(dict)
        return list

    """
    修改密码
    """

    def changePassward(self, uid, old, new1, new2):
        if new1 != None and new2 != None and \
                len(new1) >= 3 and len(new2) >= 3 and \
                new1 == new2 and uid != None:
            u = db_session.query(User).filter(User.uid == uid).first()
            if u == None:
                current_app.logger.info('查询不到用户id：{}'.format(uid))
                return 0
        current_app.logger.info('查询到用户{}'.format(u))
        if check_password_hash(u.passward, old):
            u.passward = generate_password_hash(new1)
            try:
                db_session.commit()
                current_app.logger.info('修改用户{}密码成功,新密码：{}'.format(u, generate_password_hash(u.passward)))
            except Exception as r:
                current_app.logger.error(r)
                return 0
            return 1
        else:
            current_app.logger.info('用户{}旧密码输入错误，修改失败'.format(u))
            return 0

    """
    修改手机号码
    """

    def changePhone(self, uid, passward, phone):
        if uid != None and passward != None and phone != None and \
                len(uid) > 0 and len(passward) >= 3 and len(phone) == 11:
            u = db_session.query(User).filter(User.uid == uid).first()
            if u == None:
                current_app.logger.info('查询不到用户id：{}'.format(uid))
                return 0
            current_app.logger.info('查询到用户{}'.format(u))
            u.phone = phone
            try:
                db_session.commit()
                current_app.logger.info('修改用户{}手机号码成功,新手机号：{}'.format(u, u.phone))
            except Exception as r:
                current_app.logger.error(r)
                return 0
            return 1
        else:
            current_app.logger.info('数据错误')
            return 0

    """
   修改用户名
   """

    def changeUserName(self, uid, userName):
        if uid != None and userName != None and \
                len(uid) > 0 and len(userName) >= 3:
            u = db_session.query(User).filter(User.uid == uid).first()
            if u == None:
                current_app.logger.info('查询不到用户id：{}'.format(uid))
                return 0
            current_app.logger.info('查询到用户{}'.format(u))
            u.username = userName
            try:
                db_session.commit()
                current_app.logger.info('修改用户{}用户名成功,新用户名：{}'.format(u, u.username))
            except Exception as r:
                current_app.logger.error(r)
                return 0
            return 1
        else:
            current_app.logger.info('数据错误')
            return 0

    """
    修改邮箱
    """

    def changeMail(self, uid, mail, varifiycode):
        if uid != None and mail != None and varifiycode != None and \
                len(uid) > 0 and len(mail) >= 3 and len(varifiycode) == 4:

            # 这里验证验证码
            if varifiycode != '1234':
                current_app.logger.info('验证码错误，系统验证码：{}用户输入的验证码：{}'
                                        .format(varifiycode, 1234))
                return 0

            u = db_session.query(User).filter(User.uid == uid).first()
            if u == None:
                current_app.logger.info('查询不到用户id：{}'.format(uid))
                return 0
            current_app.logger.info('查询到用户{}'.format(u))
            u.mail = mail
            try:
                db_session.commit()
                current_app.logger.info('修改用户{}邮箱成功,新邮箱：{}'.format(u, u.mail))
            except Exception as r:
                current_app.logger.error(r)
                return 0
            return 1
        else:
            current_app.logger.info('数据错误')
            return 0

    """
    注册(验证码固定)
    """

    def register(self, username, passward, phone, mail, varifiycode):
        # username需要适当的名字
        username = getRadomStr() if username == None else username
        username = getRadomStr() if len(username) < 3 else username
        mail = '' if mail == None else mail
        if passward != None and varifiycode != None and phone != None and \
                len(passward) > 3 and len(varifiycode) == 4 and len(phone) == 11:

            # 这里验证验证码
            if varifiycode != '1234':
                current_app.logger.info('验证码错误，系统验证码：{}用户输入的验证码：{}'
                                        .format(varifiycode, 1234))
                return 0

            # 查询是否已经有注册了
            u = db_session.query(User).filter(User.phone == phone).first()
            if u != None:
                current_app.logger.info('手机号{}已经注册过了'.format(phone))
                return 0

            u = User(username, generate_password_hash(passward), phone, mail, 'N', 2, 0)  # 2 设置为注册用户
            db_session.add(u)
            try:
                db_session.commit()
                current_app.logger.info('添加用户：{}'.format(u))
            except Exception as r:
                current_app.logger.error(r)
                return 0
            return 1
        else:
            current_app.logger.info('数据错误')
            return 0

    """
    登陆
    """

    def login(self, phone, passward, varifiycode):
        if phone != None and passward != None and varifiycode != None and \
                len(phone) == 11 and len(passward) >= 3 and len(varifiycode) == 4:

            # 这里验证验证码
            if varifiycode != '1234':
                current_app.logger.info('验证码错误，系统验证码：{}用户输入的验证码：{}'
                                        .format(varifiycode, 1234))
                return 0, -1
            try:
                u = db_session.query(User).filter(User.phone == phone).first()
            except Exception as r:
                current_app.logger.error(r)
                return 0, -1
            if u == None:
                current_app.logger.info('这个电话号码：{}没有注册'.format(phone))
                return 0, -1
            if not check_password_hash(u.passward, passward):
                current_app.logger.info('用户{}密码输入错误'.format(phone))
                return 0, -1
            current_app.logger.info('用户{}登陆成功'.format(phone))
            re = db_session.query(Expert).filter(Expert.userid == u.uid).first()
            if re is not None:
                return 1, u.uid, 1
            else:
                return 1, u.uid, 0
        else:
            current_app.logger.info('数据错误')
            return 0, -1

    """
    获取验证码
    """

    def getVarifyCode(self):
        code = 1234
        current_app.logger.info('验证码：{}'.format(code))
        return code

    """
    测试
    """

    def testInserExpert(self, name='未知'):
        u = Userclassifies(name)
        print(u)
        db_session.add(u)
        db_session.commit()
        id = u.id
        return id
